import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController, LoadingController} from 'ionic-angular';
import { AddressPage } from '../address/address';
import { Https } from '../../app/http.service'
/**
 * Generated class for the ChioceAddressPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-chioce-address',
  templateUrl: 'chioce-address.html',
})
export class ChioceAddressPage {
	check:string = '0' ;
	Url: string = new Https().Url + "act=goods&op=tihuoAddress"
	tigUrl: string = new Https().Url + "act=goods&op=defined_address"
	isDefaultAddressUrl = new Https().Url + "act=goods&op=app_address_default"
	data = [];
	info = 0;
	constructor(public navCtrl: NavController, public navParams: NavParams, public alertCtrl: AlertController, public loadingCtrl: LoadingController) {
	}

	ionViewDidLoad() {
		console.log('ionViewDidLoad ChioceAddressPage');
		this.loadData();
	}
	loadData() {
		let then = this;
		fetch(this.Url, {
			method: "post",
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			body: "mid=" + localStorage.getItem("mid") + "&token=" + localStorage.getItem("token"),
		}).then((data) => {

			data.text().then((json) => {
				if (json != '') {
					let resource = JSON.parse(json).datas;
					then.data = resource;
					for (let item of resource){
						if (item.is_default == '1') {
							// then.changeAddress(item.address_id);
							then.check = item.address_id
							console.log(123)
						}
					}
					
					console.log(then.check)
					then.info = 1;
				} else {
					then.info = 1;
					then.alertP('网络连接错误')
				}
			})


		}).catch((err) => {
			
			this.alertP(err)
		})
	}
	changeAddress(int){
		console.log(int);
		this.check = int;
		let then = this;
		let loader = this.loadingCtrl.create({
			content: "请稍等...",
		}); loader.present();
		console.log(int)

		fetch(this.isDefaultAddressUrl, {
			method: "post",
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			body: "mid=" + localStorage.getItem("mid") + "&token=" + localStorage.getItem("token") + "&address_id=" + int
		}).then((response) => {
			response.text().then((res) => {

				let Data = JSON.parse(res)
				console.log(Data)
				console.log(Data.datas.status)
				if (Data.datas.status == 0) {
					this.alertP("哎呀！出错了")
					loader.dismiss();
				}else{
					then.navCtrl.pop();
					loader.dismiss();
				}
			})
		}).catch((res) => {
			this.alertP("哎呀！出错了")
		})

		
	}	
	openAddress(){
		this.navCtrl.push(AddressPage)
	}
	alertP(text){
		let alert = this.alertCtrl.create({
			title: '温馨提示',
			subTitle: text,
			buttons: ['好']
		});
		alert.present();
	}
}
